<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Commodity;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;

class CommodityController extends Controller
{
   protected $guarded = [''];

   public function commodityList(Request $request)
   {
     $category_id = $request->category_id;
     $list = Commodity::where('category_id', $category_id)->paginate(10);
     return $list;

   }

    public function detail(Request $request)
    {
      $commodity_id = $request->input('commodity_id');
      $data = Commodity::where('id', $commodity_id)->get();
      return $data;
    }

    public function hotDetail(Request $request)
    {
      $commodity_id = $request->input('commodity_id');
      $data = Commodity::where('id', $commodity_id)->get();
      return $data;
    }

    public function hot()
    {
      $data = Commodity::where('is_hot', 1)->paginate(10);
      return $data;
    }

    //按照商品名称搜素
    public function search(Request $request)
    {
      //读取文章内容
        $commoditys = Commodity::orderBy('id','desc')
            ->where(function($query) use ($request){
                //检测当前的请求中是否包含keyword参数
                $keyword = $request->input('keyword', '');
                if(!empty($keyword)) {
                    $query->where('name','like','%'.$keyword.'%');
                }
            })
            ->paginate(10);
        return $commoditys;
    }

    // 商品搜索（按商品销量  从高到低） :
    public function salesVolumeDesc()
    {
      $commoditys = Commodity::where('id','>=',1) ->orderBy('sales_volume', 'desc')->paginate(10);
       // ->take(10)
       // ->get();

          // ->paginate(10);
      return $commoditys;
    }

    // 商品搜索（按商品价格  从高到低） :
    public function priceDesc()
    {

      $commoditys = Commodity::where('id','>=',1) ->orderBy('price', 'asc')->paginate(10);
       // ->take(10)
       // ->get();

          // ->paginate(10);
      return $commoditys;
    }

    //小程序首页最新10条数据显示
    public function latestData()
    {
      $data = Commodity::query()->offset(0)->take(6)->get()->toArray();
      return $data;
    }

    //商品系列返回
    public function series(Request $request)
    {
      $commodity_id = $request->input('commodity_id');
      $commodity = Commodity::find($commodity_id);
      $data = $commodity->CommoditySeries()->paginate(10);
      return $data;
    }
}
